package com.gylang.print.richtext.component;

import cn.hutool.core.util.StrUtil;
import com.gylang.print.pdf.util.PdfUtil;
import lombok.Data;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author gylang
 * data 2021/7/14
 */
@Data
public class RichBox {

	/** 页面大小 */
	private float width = 595.28F;
	/** 高度 */
	private float height = 842.28F;
	/** 边框 left */
	private float marginL = 5F;
	/** 边框 right */
	private float marginR = 5F;
	/** 边框 top */
	private float marginT = 5F;
	/** 边框 bottom */
	private float marginB = 5F;
	/** 背景 */
	private String background;
	/** 默认字体 */
	private String font = "STSONG.TTF";
	/** 默认行高 */
	private float heightLine = 1;
	/** 默认字体大小 */
	private float fontSize = 12;
	/** 默认间距 */
	private float space;

	private PDPage page;

	private PDPageContentStream contentStream;

	private PDDocument document;

	private Map<String, Object> cache = new HashMap<>();

	@SuppressWarnings("unchecked")
	public <T> T cacheObject(String key) {
		return (T) cache.get(key);
	}

	public void storeCache(String key, Object obj) {
		cache.put(key, obj);
	}

	@SuppressWarnings("unchecked")
	public <T> T cacheObject(String key, T defaultValue) {
		T t = (T) cache.get(key);
		return null != t ? t : defaultValue;
	}

	public PDPageContentStream getContentStream() {
		if (null == contentStream) {
			try {
				contentStream = new PDPageContentStream(
					document,
					getPage());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return contentStream;
	}


	public PDFont getFont(String name) {

		name = StrUtil.emptyToDefault(name, font);
		Object o = cache.get(name);
		if (null != o) {
			return (PDFont) o;
		}
		PDFont pdFont = PdfUtil.loadFontByName(document, name);
		cache.put(name, pdFont);
		return pdFont;
	}
}
